import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.math.BigDecimal;

public class ImprovedCalculator {

    private JFrame frame;
    private JTextField displayField;
    private StringBuilder inputBuffer;

    public ImprovedCalculator() {
        frame = new JFrame("Improved Calculator");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(300, 400);
        frame.setLayout(new BorderLayout());

        displayField = new JTextField();
        displayField.setEditable(false);
        frame.add(displayField, BorderLayout.NORTH);

        JPanel buttonPanel = new JPanel();
        buttonPanel.setLayout(new GridLayout(5, 4));

        addButton(buttonPanel, "7");
        addButton(buttonPanel, "8");
        addButton(buttonPanel, "9");
        addButton(buttonPanel, "/");
        addButton(buttonPanel, "4");
        addButton(buttonPanel, "5");
        addButton(buttonPanel, "6");
        addButton(buttonPanel, "*");
        addButton(buttonPanel, "1");
        addButton(buttonPanel, "2");
        addButton(buttonPanel, "3");
        addButton(buttonPanel, "-");
        addButton(buttonPanel, "0");
        addButton(buttonPanel, ".");
        addButton(buttonPanel, "=");
        addButton(buttonPanel, "+");

        frame.add(buttonPanel, BorderLayout.CENTER);

        inputBuffer = new StringBuilder();

        frame.setVisible(true);
    }

    private void addButton(Container container, String text) {
        JButton button = new JButton(text);
        button.addActionListener(new ButtonClickListener());
        container.add(button);
    }

    private class ButtonClickListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            String buttonText = ((JButton) e.getSource()).getText();

            switch (buttonText) {
                case "=":
                    calculate();
                    break;
                default:
                    inputBuffer.append(buttonText);
                    displayField.setText(inputBuffer.toString());
            }
        }

        private void calculate() {
            try {
                BigDecimal result = new BigDecimal(inputBuffer.toString());
                displayField.setText(result.toString());

                inputBuffer.setLength(0);
            } catch (Exception ex) {
                handleCalculationError();
                ex.printStackTrace();
            }
        }

        private void handleCalculationError() {
            JOptionPane.showMessageDialog(frame, "Error! Please check the input expression.", "Error", JOptionPane.ERROR_MESSAGE);
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new ImprovedCalculator();
            }
        });
    }
}
